import { useState, useEffect } from "react";
import { View, Text } from "@tarojs/components";
import {
  Checkbox,
  Collapse,
  Table,
  Input,
  Picker,
  Button,
  Pagination,
} from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { ArrowDown } from "@nutui/icons-react-taro";
import {
  getCourseRedemptionStatistics,
  getCourseRedemptionList,
} from "@/api/courseRedemption";
import dayjs from "dayjs";
import "./index.scss";

const CourseRedemption = () => {
  const { params: query } = Taro.useRouter();
  const [statisticsData, setStatisticsData] = useState<any>(undefined);
  const [checked, setChecked] = useState<any>(false);

  const [params, setParams] = useState<any>({
    code: "",
    status: "",
  });
  const [open, setOpen] = useState(false);
  const statusList = [
    { text: "未兑换", value: 1 },
    { text: "已兑换", value: 2 },
    { text: "已过期", value: 3 },
    { text: "已使用", value: 4 },
    { text: "剩余可用", value: 5 },
  ];

  const [pageNo, setPageNo] = useState<any>(1);
  const [total, setTotal] = useState<any>(0);
  const columns = [
    {
      title: "兑换码",
      align: "center",
      key: "code",
    },
    {
      title: "商家兑换码",
      align: "center",
      key: "codeV2",
    },
    {
      title: "兑换用户",
      align: "center",
      key: "usedUserName",
    },
    {
      title: "兑换时间",
      align: "center",
      key: "useTime",
      render: (row) => {
        return (
          <View>
            {row.useTime
              ? dayjs(row.useTime).format("YYYY-MM-DD HH:mm:ss")
              : "-"}
          </View>
        );
      },
    },
  ];
  const [tableData, setTableData] = useState<any[]>([]);

  const getStatistics = async () => {
    const res = await getCourseRedemptionStatistics({
      dataId: query.dataid,
    });
    setStatisticsData(res.data);
  };
  const getList = async () => {
    const res = await getCourseRedemptionList({
      dataId: query.dataid,
      pageNo,
      pageSize: 20,
      ...params,
    });
    setTableData(res.data.list);
    setTotal(res.data.total);
  };
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: query.opusName + "课程",
    });
    getStatistics();
  }, []);
  useEffect(() => {
    getList();
  }, [pageNo]);
  return (
    <View className="bg-[#F5F5F5] p-3 h-screen box-border course-redemption">
      <View className="bg-white rounded-lg items-center grid grid-cols-3 p-4 text-sm">
        <View>
          总量：<Text className="text-base">{statisticsData?.totalCount}</Text>
        </View>
        <View>
          使用量：
          <Text className="text-base">{statisticsData?.codeV2Count}</Text>
        </View>
        <View>
          剩余量：
          <Text className="text-base">{statisticsData?.noCodeV2Count}</Text>
        </View>
      </View>
      <View className="my-4 rounded-lg pr-2 pl-2 bg-white">
        <Collapse
          style={{
            ["--nutui-collapse-wrapper-content-padding" as string]: "12px",
          }}
          expandIcon={<ArrowDown />}
        >
          <Collapse.Item
            title={
              <View
                onClick={(e) => {
                  e.stopPropagation();
                }}
              >
                <Checkbox
                  checked={checked}
                  onChange={setChecked}
                  label="显示商家兑换码"
                />
              </View>
            }
            extra="筛选"
            name="1"
          >
            <View className="flex gap-2 items-center text-xs">
              兑换码
              <Input
                value={params.code}
                style={{
                  border: "1px solid rgb(0, 0, 0,0.06)",
                  flex: 1,
                }}
                onChange={(value) => {
                  setParams({ ...params, code: value });
                }}
                placeholder="请输入兑换码"
              />
              状态
              <View
                onClick={() => {
                  setOpen(true);
                }}
                className="flex-1 flex items-center relative text-md text-black"
                style={{
                  border: "1px solid rgb(0, 0, 0,0.06)",
                  height: "24.39px",
                  padding: "10px",
                }}
              >
                {statusList.find((item) => item.value === params.status)
                  ?.text || <Text className="text-gray-500">请选择状态</Text>}
                <ArrowDown
                  color="rgb(0, 0, 0,0.6)"
                  className="!absolute right-1"
                />
              </View>
            </View>
            <View className="flex justify-center mt-4">
              <Button
                onClick={() => {
                  if (pageNo === 1) {
                    getList();
                  } else {
                    setPageNo(1);
                  }
                }}
                type="primary"
              >
                搜索
              </Button>
            </View>
          </Collapse.Item>
        </Collapse>
      </View>

      <Table
        columns={
          checked ? columns : columns.filter((item) => item.key !== "codeV2")
        }
        data={tableData}
      />
      <Pagination
        className="mt-4 flex justify-center"
        value={pageNo}
        total={total}
        pageSize={20}
        onChange={setPageNo}
      />
      <Picker
        title="请选择兑换状态"
        options={statusList}
        visible={open}
        onClose={() => setOpen(false)}
        onConfirm={(value) => {
          setParams({ ...params, status: value[0]?.value });
        }}
      />
    </View>
  );
};

export default CourseRedemption;
